/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys.utils;

import com.thinkgem.jeesite.common.service.ServiceException;
import com.thinkgem.jeesite.common.utils.SessionUtils;
import com.thinkgem.jeesite.common.utils.SpringContextHolder;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.sys.entity.*;
import com.thinkgem.jeesite.modules.sys.security.SystemAuthorizingRealm.Principal;
import com.thinkgem.jeesite.modules.sys.service.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.subject.Subject;

import java.util.List;

/**
 * 用户工具类
 *
 * @author kongxiangsheng
 * @version 2013-12-05
 */
public class UserUtils {
    private static SysUserService sysUserService = SpringContextHolder.getBean(SysUserService.class);
    private static SysRoleService sysRoleService = SpringContextHolder.getBean(SysRoleService.class);
    private static SysMenuService sysMenuService = SpringContextHolder.getBean(SysMenuService.class);
    private static SysAreaService sysAreaService = SpringContextHolder.getBean(SysAreaService.class);
    private static SysOfficeService sysOfficeService = SpringContextHolder.getBean(SysOfficeService.class);

    // #################  用户相关--begin  #################

    /**
     * 根据ID获取用户
     *
     * @param userId
     * @return 取不到返回null
     */
    public static SysUser get(String userId) {
        return sysUserService.get(userId);
    }

    /**
     * 获取当前登陆用户的ID
     *
     * @return
     */
    public static String getCurrentUserId() {
        SysUser sysUser = getUser();
        if (StringUtils.isBlank(sysUser.getId())) {
            throw new ServiceException("获取当前登陆用户信息失败！");
        }
        return sysUser.getId();
    }

    /**
     * 根据登录名获取用户
     *
     * @param loginName
     * @return 取不到返回null
     */
    public static SysUser getByLoginName(String loginName) {
        return sysUserService.getByLoginName(loginName);
    }

    /**
     * 根据ID获取用户名称
     *
     * @param userId
     * @return
     */
    public static String getUserName(String userId) {
        SysUser sysUser = sysUserService.get(userId);
        return null == sysUser ? "" : sysUser.getName();
    }

    /**
     * 根据用户ID获取用户所在公司名称
     *
     * @param userId
     * @return
     */
    public static String getUserCompanyName(String userId) {
        SysUser sysUser = sysUserService.get(userId);
        if (null == sysUser) {
            return "";
        }
        SysOffice company = getOffice(sysUser.getCompanyId());
        if (null == company) {
            return "";
        }
        return company.getName();
    }

    /**
     * 根据用户ID获取用户所在部门名称
     *
     * @param userId
     * @return
     */
    public static String getUserOfficeName(String userId) {
        SysUser sysUser = sysUserService.get(userId);
        if (null == sysUser) {
            return "";
        }
        SysOffice sysOffice = getOffice(sysUser.getOfficeId());
        if (null == sysOffice) {
            return "";
        }
        return sysOffice.getName();
    }

    /**
     * 获取用户所属机构的详细路径
     *
     * @param userId
     * @return
     */
    public static String getUserOfficePath(String userId) {
        SysUser sysUser = sysUserService.get(userId);
        if (null == sysUser) {
            return "";
        }
        String officeNamePath = sysOfficeService.getOfficeNamePath(sysUser.getOfficeId());
        return officeNamePath;
    }
    // #################  用户相关--end  #################

    // #################  机构相关--begin  #################

    /**
     * 根据id获取机构信息
     *
     * @param id
     * @return
     */
    public static SysOffice getOffice(String id) {
        return sysOfficeService.get(id);
    }

    /**
     * 根据ID获取机构名称
     *
     * @param id
     * @return
     */
    public static String getOfficeName(String id) {
        SysOffice sysOffice = sysOfficeService.get(id);
        return null == sysOffice ? "" : sysOffice.getName();
    }

    // #################  机构相关--end  #################

    // #################  区域相关--end  #################

    /**
     * 根据id获取区域信息
     *
     * @param areaId
     * @return
     */
    public static SysArea getArea(String areaId) {
        return sysAreaService.get(areaId);
    }

    /**
     * 根据ID获取区域名称
     *
     * @param areaId
     * @return
     */
    public static String getAreaName(String areaId) {
        SysArea sysArea = getArea(areaId);
        return null == sysArea ? "" : sysArea.getName();
    }

    // #################  区域相关--end  #################

    /**
     * 获取当前用户
     *
     * @return 取不到返回 new SysUser()
     */
    public static SysUser getUser() {
        Principal principal = getPrincipal();
        if (principal != null) {
            SysUser sysUser = get(principal.getId());
            if (sysUser != null) {
                return sysUser;
            }
            return new SysUser();
        }
        // 如果没有登录，则返回实例化空的User对象。
        return new SysUser();
    }

    /**
     * 获取授权主要对象
     */
    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    /**
     * 获取当前登录者对象
     */
    public static Principal getPrincipal() {
        try {
            Subject subject = SecurityUtils.getSubject();
            Principal principal = (Principal) subject.getPrincipal();
            if (principal != null) {
                return principal;
            }
//			subject.logout();
        } catch (UnavailableSecurityManagerException e) {

        } catch (InvalidSessionException e) {

        }
        return null;
    }

    // ============== session cache begin ==============

    /**
     * 获取当前用户角色列表
     *
     * @return
     */
    public static List<SysRole> getRoleList() {
        List<SysRole> roleList = (List<SysRole>) SessionUtils.getAttrRole();
        if (null == roleList) {
            SysUser sysUser = getUser();
            if (sysUser.isAdmin()) {
                roleList = sysRoleService.selectRollListAll();
            } else {
                roleList = sysRoleService.selectRollList();
            }
            SessionUtils.putAttrRole(roleList);
        }
        return roleList;
    }

    /**
     * 获取当前用户授权菜单
     *
     * @return
     */
    public static List<SysMenu> getMenuList() {
        SysUser sysUser = getUser();
        if (sysUser.isAdmin()) {
            return sysMenuService.getAllOrdered();
        } else {
            return sysMenuService.findByUserId(sysUser.getId());
        }
    }

    /**
     * 获取当前用户授权的区域
     *
     * @return
     */
    public static List<SysArea> getAreaList() {
        @SuppressWarnings("unchecked")
        List<SysArea> areaList = (List<SysArea>) SessionUtils.getAttrArea();
        if (null == areaList) {
            areaList = sysAreaService.getAllOrdered();
            SessionUtils.putAttrArea(areaList);
        }
        return areaList;
    }

    /**
     * 获取当前用户有权限访问的部门
     *
     * @return
     */
    public static List<SysOffice> getOfficeList() {
        SysUser sysUser = getUser();
        List<SysOffice> officeList = (List<SysOffice>) SessionUtils.getAttrOffice();
        if (null == officeList) {
            if (sysUser.isAdmin()) {
                officeList = sysOfficeService.selectAll();
            } else {
                officeList = sysOfficeService.selectWithChildren(sysUser.getCompanyId());
            }
            SessionUtils.putAttrOffice(officeList);
        }
        return officeList;
    }

    /**
     * 获取所有机构信息
     *
     * @return
     */
    public static List<SysOffice> getAllOfficeList() {
        List<SysOffice> officeList = (List<SysOffice>) SessionUtils.getAttrOfficeAll();
        if (null == officeList) {
            officeList = sysOfficeService.selectAll();
            SessionUtils.putAttrOfficeAll(officeList);
        }
        return officeList;
    }

}
